package com.lecture.java8.drools;

import org.kie.api.KieServices;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.stereotype.Component;

@Component
public class KieBaseUpdater {
    private final KieContainer kieContainer;
    private final KieServices kieServices;

    public KieBaseUpdater(KieContainer kieContainer, KieServices kieServices) {
        this.kieContainer = kieContainer;
        this.kieServices = kieServices;
    }

    public void updateKieBase(String ruleString) {
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        kieFileSystem.write(ResourceFactory.newByteArrayResource(ruleString.getBytes()));
        kieServices.newKieBuilder(kieFileSystem).buildAll();
        kieContainer.updateToVersion(kieContainer.getReleaseId());
    }

    public KieSession getKieSession() {
        return kieContainer.newKieSession();
    }
}

